﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BlogPost.cs" company="Tobias Lekman">
//   Licensed under Microsoft Public License (Ms-PL). See lekman.codeplex.com/license for more information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace LekmanCom.Controls
{
    using System;
    using System.Text.RegularExpressions;
    using System.Xml.Linq;

    /// <summary>
    /// Represents the data from a blog post.
    /// </summary>
    public class BlogPost
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BlogPost"/> class.
        /// </summary>
        /// <param name="blogPost">
        /// The blog post.
        /// </param>
        public BlogPost(XContainer blogPost)
        {
            if (blogPost == null)
            {
                throw new ArgumentNullException("blogPost");
            }

            XElement title = blogPost.Element("title");
            if (title != null)
            {
                this.Title = title.Value;
            }

            XElement link = blogPost.Element("link");
            if (link != null)
            {
                this.Link = link.Value;
            }

            XElement summary = blogPost.Element("description");
            if (summary != null)
            {
                this.Summary = Summarize(summary.Value);
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Link.
        /// </summary>
        public string Link { get; private set; }

        /// <summary>
        /// Gets the summary.
        /// </summary>
        public string Summary { get; private set; }

        /// <summary>
        /// Gets the title.
        /// </summary>
        public string Title { get; private set; }

        #endregion

        #region Methods

        /// <summary>
        /// Summarizes the specified value.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <returns>
        /// A summary of the value.
        /// </returns>
        private static string Summarize(string value)
        {
            const int maxLength = 250;

            value = Regex.Replace(value, "<[^>]*>", string.Empty, RegexOptions.Compiled);

            if (value.Length > maxLength)
            {
                value = value.Substring(0, maxLength);
                value = value.Substring(0, value.LastIndexOf(" ")) + "...";
            }

            return value;
        }

        #endregion
    }
}